import request from './config';

// 获取文件列表
export const getFileList = (userId: string) => {
  return request.get(`/api/files/list/${userId}`);
};

// 上传单个文件
export const uploadFile = (file: File, userId: string, folderId: string | null = null) => {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('userId', userId);
  if (folderId) {
    formData.append('folderId', folderId);
  }
  
  return request.post('/api/files/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
};

// 上传多个文件
export const uploadMultipleFiles = async (files: File[], userId: string, folderId: string | null = null) => {
  const maxFilesPerRequest = 200; // 设置最大文件数量为 200
  const totalFiles = files.length;

  // 如果文件数量不超过 200 个，直接调用多文件上传接口
  if (totalFiles <= maxFilesPerRequest) {
      const formData = new FormData();
      files.forEach(file => {
          formData.append('files', file);
      });
      formData.append('userId', userId);
      
      if (folderId) {
          formData.append('folderId', folderId);
      }
      
      console.log(folderId);
      return request.post('/api/files/upload-multiple', formData, {
          headers: {
              'Content-Type': 'multipart/form-data'
          }
      });
  } else {
      // 如果文件数量超过 200 个，分批次上传
      const uploadPromises = []; // 用于存储每个上传请求的 Promise

      for (let i = 0; i < totalFiles; i += maxFilesPerRequest) {
          const filesBatch = files.slice(i, i + maxFilesPerRequest);
          const formData = new FormData();
          filesBatch.forEach(file => {
              formData.append('files', file);
          });
          formData.append('userId', userId);
          
          if (folderId) {
              formData.append('folderId', folderId);
          }
          
          console.log(`Uploading batch ${Math.floor(i / maxFilesPerRequest) + 1} with folderId: ${folderId}`);
          // 将每个上传请求的 Promise 添加到数组中
          uploadPromises.push(
              request.post('/api/files/upload-multiple', formData, {
                  headers: {
                      'Content-Type': 'multipart/form-data'
                  }
              })
          );
      }

      // 等待所有上传请求完成
      return Promise.all(uploadPromises)
          .then(responses => {
              console.log('All batches uploaded successfully:', responses);
              return responses; // 返回所有响应
          })
          .catch(error => {
              console.error('Error uploading batches:', error);
              throw error; // 抛出错误以便处理
          });
  }
};

// 下载文件
export const downloadFile = (fileId: string) => {
  return request.get(`/api/files/download/${fileId}`, {
    responseType: 'blob'
  });
};

// 删除文件
export const deleteFile = (fileId: string) => {
  return request.delete(`/api/files/${fileId}`);
};

// 分享文件
export const shareFile = (fileId: string, sharedBy: string, sharedWith: string) => {
  return request.post('/api/files/share', {
    fileId,
    sharedBy,
    sharedWith
  });
};

// 获取文件预览URL
export const getFilePreviewUrl = async (fileId: string) => {
  return request.get(`/api/files/preview/${fileId}`);
};

// 重命名文件
export const renameFile = (fileId: string, newName: string, userId: string) => {
  return request.put(`/api/files/rename/${fileId}`, {
    newName,
    userId
  });
};